﻿using System;
using Adalbertus.BudgetPlanner.Domain;
using Adalbertus.BudgetPlanner.Domain.Repositories;

namespace Adalbertus.BudgetPlanner.Services
{
    public class IncomeService : BaseService<Income>, IIncomeService
    {
        public IncomeService(IRepositoryFactory repositoryFactory, IUnitOfWorkProvider unitOfWorkProvider)
            : base(repositoryFactory, unitOfWorkProvider)
        {
        }

        public Income Create(string name)
        {
            using (IUnitOfWork unitOfWork = UnitOfWorkProvider.OpenUnitOfWork())
            {
                Income income = new Income { Name = name };
                IRepository<Income> incomeRepository = RepositoryFactory.CreateRepository<Income>(unitOfWork);
                incomeRepository.Save(income);

                unitOfWork.Commit();
                return income;
            }
        }

        public IncomeEntry CreateEntry(Income income, decimal value, DateTime date)
        {
            using (IUnitOfWork unitOfWork = UnitOfWorkProvider.OpenUnitOfWork())
            {
                IRepository<Income> incomeRepository = RepositoryFactory.CreateRepository<Income>(unitOfWork);

                IncomeEntry incomeEntry = new IncomeEntry
                                              {
                                                  Income = income,
                                                  Value = value,
                                                  Date = date
                                              };
                income.Entries.Add(incomeEntry);
                incomeRepository.Save(income);

                unitOfWork.Commit();
                return incomeEntry;
            }
        }

        public void RemoveEntry(IncomeEntry entry)
        {
            using (IUnitOfWork unitOfWork = UnitOfWorkProvider.OpenUnitOfWork())
            {
                entry.Income.Entries.Remove(entry);

                IRepository<Income> incomeRepository = RepositoryFactory.CreateRepository<Income>(unitOfWork);

                incomeRepository.Save(entry.Income);

                unitOfWork.Commit();
            }
        }
    }
}
